package GUI;
/**
 * Login frame for all users
 * if the login credentials are wrong the system will 
 * prompt an error
 * 
 * if the parent user is blocked the system will prompt a message
 * 
 */
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;





import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Vector;

import ServerSide.ClientConsole;
import ClientSide.ChatClient;
import Common.*;

import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import GUI.*;
import java.awt.Dimension;

public class Login extends JFrame {
	public JTextField UserName;
	public JPasswordField Password;
	
	public static ChatClient client=null;
	private JButton loginButton=null;
	public JPanel FirstPanel=null;
//	private Student st=null;
	public String msg=null;
	public String UserType=null;
	public String LoginResult=null;
	public String userID=null;
	public boolean test=false;
	private JFrame err=null;
	private StudentMainMenu stmn=null;
	private AdminMainMenu amn=null;
	private TeacherMainMenu tmn=null;
	private ParentMainMenu pmn=null;
	private PrincipleMainMenu prmn=null;
	private ManagmentMainMenu mmn=null;
	public UserStudent us=null;
	public DataForParentalBlock ParentalBlock=null;
	public String taskNum;
	public static Dimension defaultDim;
	public String SYear=null;
	public String EYear=null;
	public boolean status=true;

	/**
	 * @wbp.nonvisual location=181,9
	 * 
	 * 
	 */

	public void  setChat (ChatClient cc)
	{
		if(client==null)
		{
			
			client=cc;
			
		}
		
		
	}
	
	public void setText(String msg)
	{
		String[] result=null;
		result=msg.split(" ");
		//this.st.idTextField.setText(result[1]);
		//this.st.userTypeTextField.setText(result[2]);
		//this.st.UserType=result[2];
		this.UserType=result[2];
	
		this.LoginResult=result[1];
		
		this.userID=result[0];
		//this.us.StudentData=new StudentClass("a","b",this.userID,"a");
		System.out.println("\n"+ result[0] +result[1] +result[2]);
		
		System.out.println("\n in set text to gui");
	}
	

	public void SetYears(String msg1,String msg2)
	
	{
		
	this.SYear=msg1;
	this.us.StudentData.SYear=msg1;
	this.EYear=msg2;
	this.us.StudentData.EYear=msg1;
	System.out.println("\n in set years"+this.SYear+this.EYear);
	}
	
	public void setStudentCoursesData(Courses c,Vector<String> y,Vector<String> s )
	{
		stmn.user.StudentData.ListOfCourses=c;
		stmn.user.StudentData.Years=y;
		stmn.user.StudentData.Semesters=s;
		
	}
	
	public void setChildrenToParent(Vector<String> sids, int count)
	{
		pmn.user.ChildIds=sids;
		pmn.user.numOfChildren=count;
		//for(int i=0; i<pmn.user.ChildIds.size();i++) 
			//client.handleMessageFromClientUI("PersonalDataForParent "+pmn.user.ChildIds.get(i));
	}
	
	public void setChildrenCoursesToParent(String sid,Courses c,Vector<String> y,Vector<String> s )
	{
		pmn.user.StudentsData.add(new StudentClass(sid,c,y,s));
		
			 
	}
	public void setStudCoursesToPrinciple(String sid,Courses c,Vector<String> y,Vector<String> s )
	{
		prmn.user.StudentsData.add(new StudentClass(sid,c,y,s));
	}
	
	public void SetDataStatusPrinciple(Boolean b)
	{
		prmn.user.datastatus=b;
	}
	public void SetStudentPdata(String Fn,String Ln,String Cn)
	{
		stmn.user.StudentData.FirstName=Fn;
		stmn.user.StudentData.LastName=Ln;
		stmn.user.StudentData.ClassId=Cn;
	}
	public void SetStudentPdataForParent (String sid,String Fn,String Ln,String Cn)
	{
		System.out.println("\n Set data to parent - first"+pmn.user.StudentsData.firstElement().Sid );
		
		
		for(int i=0;i<pmn.user.StudentsData.size();i++)
		{
			//System.out.println("\n i= "+i);
			StudentClass st=new StudentClass();
			if(pmn.user.StudentsData.get(i).Sid.equalsIgnoreCase(sid))
			{
				System.out.println("\n found match");
				st=pmn.user.StudentsData.get(i);
			
				System.out.println("\n found match at "+st.Sid);
				pmn.user.StudentsData.remove(i);
				st.FirstName=Fn;
				st.LastName=Ln;
				st.ClassId=Cn;
				System.out.println("\n Set data to "+st.FirstName+" "+st.LastName);
				pmn.user.StudentsData.insertElementAt(st, i);
				this.status=false;
			}	
		}
	}
	public void SetStudentPdataForPrinciple (String sid,String Fn,String Ln,String Cn)
	{
		System.out.println("\n Set data to principle - first"+prmn.user.StudentsData.firstElement().Sid );
		
		
		for(int i=0;i<prmn.user.StudentsData.size();i++)
		{
			//System.out.println("\n i= "+i);
			StudentClass st=new StudentClass();
			if(prmn.user.StudentsData.get(i).Sid.equalsIgnoreCase(sid))
			{
				System.out.println("\n found match");
				st=prmn.user.StudentsData.get(i);
			
				System.out.println("\n found match at "+st.Sid);
				prmn.user.StudentsData.remove(i);
				st.FirstName=Fn;
				st.LastName=Ln;
				st.ClassId=Cn;
				System.out.println("\n Set data to "+st.FirstName+" "+st.LastName);
				prmn.user.StudentsData.insertElementAt(st, i);
				
			}	
		}
		this.status=false;
	}
	public void setParentalBlockData(Vector<ParentClass> p)
	{
		this.ParentalBlock.Parents=p;
	}
	
	private JButton CreateloginButton()
	{
		if(loginButton==null)
		{
			loginButton=new JButton();
			loginButton.setBounds(new Rectangle(54, 129, 172, 29));
			loginButton.setText("Login");
			loginButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e)
				{
					System.out.println("actionPerformed");
					
					 try {
						
						client.openConnection();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						System.out.println("Failed to open a connection");
						e1.printStackTrace();
						
					}
				client.handleMessageFromClientUI("login "+UserName.getText().toString()+" "+Password.getText().toString());
					//while(!test);
					//setContentPane(st);
				//}
				
				//else err=new ErrMsg();
				//if (LoginResult.equalsIgnoreCase("FAILED")) 
				while(LoginResult==null);
				while(UserType==null);
				ParentalBlock.Parents=null;
				client.handleMessageFromClientUI("ParentQueryForManagment blocked");
				
				while(ParentalBlock.Parents==null);
				if(LoginResult.equalsIgnoreCase("FAILED")) 
				{JOptionPane.showMessageDialog(FirstPanel, "Error: Login Failed");
				LoginResult=null;
				UserName.setText("");
				Password.setText("");
				}
				else {
					//setContentPane(st);
					if(UserType.equalsIgnoreCase("Student"))
					{
						stmn.user=new UserStudent();
						stmn.user.SetId(userID);
						//stmn.
						client.handleMessageFromClientUI("StudentCoursesQuery "+userID.toString());
						client.handleMessageFromClientUI("PersonalDataForStudent "+userID.toString());
						
						
						while(stmn.user.StudentData.ListOfCourses==null);
						while(stmn.user.StudentData.ClassId==null);
						stmn.setVisible(true);
						setVisible(false);
					}
					else if(UserType.equalsIgnoreCase("Administrator"))
					{
						amn.setVisible(true);
						setVisible(false);
					}
					else if(UserType.equalsIgnoreCase("Teacher"))
					{
						tmn.setVisible(true);
						setVisible(false);
					}
					else if(UserType.equalsIgnoreCase("Parent"))
					{
						ParentClass temp=new ParentClass();
						for(int i=0;i<ParentalBlock.Parents.size();i++)
						{
							temp=ParentalBlock.Parents.get(i);
							if(temp.Pid.equalsIgnoreCase(UserName.getText().toString()))
								break;
							
						}
						if(temp.Blocked)
							{
								JOptionPane.showMessageDialog(FirstPanel, "Error: Your user is blocked");
								LoginResult=null;
								client.handleMessageFromClientUI("logout "+UserName.getText().toString());
								UserName.setText("");
								Password.setText("");
								//client.handleMessageFromClientUI("logout "+UserName.getText().toString());
							}
						else{
								pmn.user=new UserParent();
								pmn.user.SetId(userID);
								pmn.user.StudentsData=new Vector<StudentClass>();
								
								client.handleMessageFromClientUI("ChildQuery "+userID.toString());
								while(pmn.user.ChildIds==null);
								while(pmn.user.StudentsData==null);
								while(pmn.user.ChildIds.size()>pmn.user.StudentsData.size());
								for(int i=0; i<pmn.user.ChildIds.size();i++)
								{
								String array=pmn.user.StudentsData.get(i).Sid;
								status=true;
								client.handleMessageFromClientUI("PersonalDataForParent "+array);
								while(status);
							}
							//while(pmn.user.StudentsData.get(0).FirstName==null);
							//System.out.println("\n The first Child is "+ pmn.user.StudentsData.get(0).FirstName);
							
							pmn.setVisible(true);
							pmn.setNumOfChildren(pmn.user.numOfChildren);
							setVisible(false);
						}
					}
					else if(UserType.equalsIgnoreCase("Principle"))
					{
						prmn.user=new UserPrinciple();
						prmn.user.StudentsData=new Vector<StudentClass>();
						client.handleMessageFromClientUI("StudentsQuery");
						while(!prmn.user.datastatus);
						for(int i=0; i<prmn.user.StudentsData.size()-1;i++)
							{
								String array=prmn.user.StudentsData.get(i).Sid;
								status=true;
								client.handleMessageFromClientUI("PersonalDataForPrinciple "+array);
								while(status);//
								
							}
						prmn.setVisible(true);
						setVisible(false);
					}
					else if(UserType.equalsIgnoreCase("Managment"))
					{
						mmn.user=new UserManagment();
						mmn.setVisible(true);
						setVisible(false);
						
					}
				}
				}
					
			});
				
			
		}
		return loginButton;
		}
	
	public Login(){
		super();
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
			System.out.println("\n window closed");
			try {
			client.closeConnection();
			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
			}
			});
		initialize();
		
	}
	
	private void initialize(){
		//this.setSize(291,250);
		//this.setSize(defaultDim=new Dimension(600,600));
		this.setContentPane(getFirstPanel());
//		this.st=new Student();
//		st.setMyFrame(this);
		//this.setContentPane(st);
		this.setTitle("Login");
		this.stmn=new StudentMainMenu();
		this.amn=new AdminMainMenu();
		this.tmn=new TeacherMainMenu();
		this.pmn = new ParentMainMenu();
		this.prmn = new PrincipleMainMenu();
		this.mmn=new ManagmentMainMenu();
		stmn.myLoginFrame=this;
		amn.myLoginFrame=this;
		tmn.myLoginFrame=this;
		pmn.myLoginFrame=this;
		prmn.myLoginFrame=this;
		mmn.myLoginFrame=this;
		this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
		//this.us=
		stmn.user=new UserStudent();
		pmn.user=new UserParent();
		prmn.user=new UserPrinciple();
		mmn.user=new UserManagment();
		this.ParentalBlock=new DataForParentalBlock();
		
		
	
		
	}
	
	public JPanel getFirstPanel()
	{
		if(FirstPanel==null){
			FirstPanel=new JPanel();
			FirstPanel.setLayout(null);
			FirstPanel.setSize(getMaximumSize());
			FirstPanel.add(CreateloginButton(),null);
			
			UserName = new JTextField();
			UserName.setBounds(123, 32, 86, 20);
			FirstPanel.add(UserName);
			UserName.setColumns(10);
			
			Password = new JPasswordField();
			Password.setBounds(123, 85, 86, 20);
			FirstPanel.add(Password);
			Password.setColumns(10);
			
			
		
			JLabel lblUserName = new JLabel("User name:");
			lblUserName.setBounds(54, 28, 66, 29);
			FirstPanel.add(lblUserName);
			
			JLabel lblPassword = new JLabel("Password:");
			lblPassword.setBounds(54, 87, 59, 17);
			FirstPanel.add(lblPassword);
			
		}
		
		return FirstPanel;
			
	}
	
	public AdminMainMenu getAdminMenu()
	{
		return this.amn;
	}
	
	public ManagmentMainMenu getManagmentMainMenu()
	{
		return this.mmn;
	}
	public PrincipleMainMenu getPrincipleMainMenu()
	{
		return this.prmn;
	}
    ////////////////////////
	public StudentMainMenu getStudentMainMenu(){
	 return this.stmn;
	}
	///////////////////////////

	
	
	//private final JLabel label = DefaultComponentFactory.getInstance().createTitle("Login");
	
	/*public Login() {
		
		JPanel panel = new JPanel();
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
		);
		
		UserName = new JTextField();
		UserName.setColumns(10);
		
		JTextPane textPane = new JTextPane();
		
		JLabel lblUserId = new JLabel("User ID:");
		
		JLabel lblPassword = new JLabel("Password:");
		
		Password = new JTextField();
		Password.setColumns(10);
		
	}*/
	
	
	/*	JButton btnLogin = new JButton("Login");
		btnLogin.setVisible(true);
		
		
		//TODO seperate between definition and creation;
		btnLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			
				
			if((UserName.getText().compareTo("")!=0)||(Password.getText().compareTo("")!=0))
			{
				//btnLogin.setVisible(true);
				chat.handleMessageFromClientUI("login,"+UserName.getText() + Password.getText());
				
				
			}
				
				
				
				
			}
		});
	
		JButton btnClear = new JButton("Clear");
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(20)
					.addComponent(textPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addComponent(lblUserId)
						.addComponent(lblPassword))
					.addGap(30)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addComponent(Password, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(UserName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(238, Short.MAX_VALUE))
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap(276, Short.MAX_VALUE)
					.addComponent(btnClear)
					.addGap(18)
					.addComponent(btnLogin)
					.addGap(26))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(21)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
							.addComponent(UserName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addComponent(lblUserId))
						.addComponent(textPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblPassword)
						.addComponent(Password, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(134)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnLogin)
						.addComponent(btnClear))
					.addContainerGap(26, Short.MAX_VALUE))
		);
		panel.setLayout(gl_panel);
		getContentPane().setLayout(groupLayout);
	}
	
	*/
	/**
	 * @param args
	 */
	public static void main(String host, int port) {
		
		//ClientConsole cc = new ClientConsole(host,port);
		/*Dimension d = new Dimension(500,500);
		JFrame j = new Login();
		j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		j.setVisible(true);
		j.setSize(d);*/
		
		Login loginFrame=new Login();
		loginFrame.setSize(defaultDim=new Dimension(600,600));
		loginFrame.setVisible(true);
		
		// TODO Auto-generated method stub

	}
}
